package com.example.asus.picsel;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.picsel.cropimg.view.CropImageView;
import com.example.asus.picsel.photoview.PhotoView;
import com.example.asus.picsel.photoview.PhotoViewAttacher;
import com.example.asus.picselector.activity.BaseActivity;
import com.example.asus.picselector.constants.Constants;
import com.example.asus.picselector.R;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;

public class EduMyPicturePreviewActivity extends BaseActivity {
    public static final int RESULT_SEND = 1;
    private TextView mIndexTotal;
    private View mWholeView;
    private View mToolbarTop;
    private View mToolbarBottom;
    private ImageButton mBtnBack;
    private Button mBtnSend;
    private CheckButton mUseOrigin;
    private CheckButton mSelectBox;
    private MyHackyViewPager mViewPager;
    private ArrayList<EduMyPictureSelectorActivity.PicItem> mItemList;
    private ArrayList<EduMyPictureSelectorActivity.PicItem> mItemSelectedList;
    private int mCurrentIndex;
    private boolean mFullScreen;
    private String sendName;
    private boolean editheaad;
    private CropImageView cropImageView;
    private boolean isSelect;
    private int imgMaxNumber = (Constants.PIC_MAX_NUMEBR - 1);
    private int imgMaxNumberSelect;

    public EduMyPicturePreviewActivity() {
    }

    @Override
    protected void setContentView() {
        this.requestWindowFeature(1);
        //透明状态栏
//        StatusBarUtil2.setStatusTextColor(false, this);
        this.setContentView(R.layout.activity_edu_picprev);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        editheaad = getIntent().getBooleanExtra(Constants.PIC_EDIT, false);
        sendName = getIntent().getStringExtra(Constants.PIC_SEND);
        isSelect = getIntent().getBooleanExtra(Constants.PIC_ISSELECT, false);
        imgMaxNumber = getIntent().getIntExtra(Constants.PIC_MAX, (Constants.PIC_MAX_NUMEBR - 1));
        imgMaxNumberSelect = getIntent().getIntExtra(Constants.PIC_MAX_SELECT, 0);
        this.initView();
        this.mUseOrigin.setChecked(this.getIntent().getBooleanExtra("sendOrigin", false));
        this.mCurrentIndex = this.getIntent().getIntExtra("index", 0);
        if (this.mItemList == null) {
            this.mItemList = EduMyPictureSelectorActivity.PicItemHolder.itemList;
            this.mItemSelectedList = EduMyPictureSelectorActivity.PicItemHolder.itemSelectedList;
        }

        if (this.mItemList != null)
            this.mIndexTotal.setText(String.format("%d/%d", this.mCurrentIndex + 1, this.mItemList.size()));
        int result;
        if (Build.VERSION.SDK_INT >= 11) {
            this.mWholeView.setSystemUiVisibility(1024);
            result = getSmartBarHeight(this);
            if (result > 0) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)this.mToolbarBottom.getLayoutParams();
                lp.setMargins(0, 0, 0, result);
                this.mToolbarBottom.setLayoutParams(lp);
            }
        }

        result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(this.mToolbarTop.getLayoutParams());
        lp.setMargins(0, result, 0, 0);
//        this.mToolbarTop.setLayoutParams(lp);
        this.mBtnBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("sendOrigin", EduMyPicturePreviewActivity.this.mUseOrigin.getChecked());
                EduMyPicturePreviewActivity.this.setResult(-1, intent);
                EduMyPicturePreviewActivity.this.finish();
            }
        });
        this.mBtnSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent data = new Intent();
                ArrayList<Uri> list = new ArrayList();
                Iterator var4;
                EduMyPictureSelectorActivity.PicItem item;
                if(!editheaad){
                    if (EduMyPicturePreviewActivity.this.mItemSelectedList != null) {
                        var4 = EduMyPicturePreviewActivity.this.mItemSelectedList.iterator();

                        while(var4.hasNext()) {
                            item = (EduMyPictureSelectorActivity.PicItem)var4.next();
                            if (item.selected) {
                                list.add(Uri.parse("file://" + item.uri));
                            }
                        }
                    }

                    var4 = EduMyPicturePreviewActivity.this.mItemList.iterator();

                    while(var4.hasNext()) {
                        item = (EduMyPictureSelectorActivity.PicItem)var4.next();
                        if (item.selected) {
                            list.add(Uri.parse("file://" + item.uri));
                        }
                    }
                }else {
                    //获取裁剪的图片
                    Bitmap cropBitMap = cropImageView.getCroppedImage();
                    File file = Utils.saveBitmap(EduMyPicturePreviewActivity.this, cropBitMap, "heads.jpg");
                    cropImageView.setImageBitmap(cropBitMap);
                    list.add(Uri.parse("file://" + file.getPath()));
//                    item = EduMyPicturePreviewActivity.this.mItemList.get(mCurrentIndex);
//                    list.add(Uri.parse("file://" + item.uri));
                }
                data.putExtra("sendOrigin", EduMyPicturePreviewActivity.this.mUseOrigin.getChecked());
                data.putExtra("android.intent.extra.RETURN_RESULT", list);
                EduMyPicturePreviewActivity.this.setResult(1, data);
                EduMyPicturePreviewActivity.this.finish();
            }
        });
        this.mUseOrigin.setText(R.string.edu_pic_sel_text_12);
        this.mUseOrigin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EduMyPicturePreviewActivity.this.mUseOrigin.setChecked(!EduMyPicturePreviewActivity.this.mUseOrigin.getChecked());
                if (EduMyPicturePreviewActivity.this.mUseOrigin.getChecked() && EduMyPicturePreviewActivity.this.getTotalSelectedNum() == 0) {
                    EduMyPicturePreviewActivity.this.mSelectBox.setChecked(!EduMyPicturePreviewActivity.this.mSelectBox.getChecked());
                    ((EduMyPictureSelectorActivity.PicItem)EduMyPicturePreviewActivity.this.mItemList.get(EduMyPicturePreviewActivity.this.mCurrentIndex)).selected = EduMyPicturePreviewActivity.this.mSelectBox.getChecked();
                    EduMyPicturePreviewActivity.this.updateToolbar();
                }

            }
        });
        this.mSelectBox.setText(R.string.edu_pic_sel_text_13);
        this.mSelectBox.setChecked(((EduMyPictureSelectorActivity.PicItem)this.mItemList.get(this.mCurrentIndex)).selected);
        this.mSelectBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!EduMyPicturePreviewActivity.this.mSelectBox.getChecked() && EduMyPicturePreviewActivity.this.getTotalSelectedNum() == imgMaxNumber) {
                    Toast.makeText(EduMyPicturePreviewActivity.this.getApplicationContext(), "您最多只能选择"+imgMaxNumber+"张图片", Toast.LENGTH_SHORT).show();
//                    if(isSelect){
//                        Toast.makeText(EduMyPicturePreviewActivity.this.getApplicationContext(), "您已经选择了"+imgMaxNumberSelect+"张图片上传", Toast.LENGTH_SHORT).show();
//                    }else {
//                        Toast.makeText(EduMyPicturePreviewActivity.this.getApplicationContext(), "您最多只能选择"+imgMaxNumber+"张图片", Toast.LENGTH_SHORT).show();
//                    }
                } else {
                    EduMyPicturePreviewActivity.this.mSelectBox.setChecked(!EduMyPicturePreviewActivity.this.mSelectBox.getChecked());
                    ((EduMyPictureSelectorActivity.PicItem)EduMyPicturePreviewActivity.this.mItemList.get(EduMyPicturePreviewActivity.this.mCurrentIndex)).selected = EduMyPicturePreviewActivity.this.mSelectBox.getChecked();
                    EduMyPicturePreviewActivity.this.updateToolbar();
                }
            }
        });
        this.mViewPager.setAdapter(new PreviewAdapter());
        this.mViewPager.setCurrentItem(this.mCurrentIndex);
        this.mViewPager.setOffscreenPageLimit(1);
        this.mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
                EduMyPicturePreviewActivity.this.mCurrentIndex = position;
                EduMyPicturePreviewActivity.this.mIndexTotal.setText(String.format("%d/%d", position + 1, EduMyPicturePreviewActivity.this.mItemList.size()));
                EduMyPicturePreviewActivity.this.mSelectBox.setChecked(((EduMyPictureSelectorActivity.PicItem)EduMyPicturePreviewActivity.this.mItemList.get(position)).selected);
            }

            public void onPageScrollStateChanged(int state) {
            }
        });
        this.updateToolbar();
        if(editheaad){
            cropImageView = (CropImageView) findViewById(R.id.CropImageView);
            cropImageView.setImageBitmap(Utils.getSmallBitmap(EduMyPicturePreviewActivity.this.mItemList.get(mCurrentIndex).uri));
//            cropImageView.setAspectRatio(5);
//            cropImageView.setFixedAspectRatio(true);
//            cropImageView.setGuidelines(2);
        }
    }

    private void initView() {
        this.mToolbarTop = this.findViewById(R.id.toolbar_top);
        this.mIndexTotal = (TextView)this.findViewById(R.id.index_total);
        this.mBtnBack = (ImageButton)this.findViewById(R.id.back);
        this.mBtnSend = (Button)this.findViewById(R.id.send);
        if(!TextUtils.isEmpty(sendName)){
            this.mBtnSend.setText(sendName+"");
        }
        this.mWholeView = this.findViewById(R.id.whole_layout);
        this.mViewPager = (MyHackyViewPager)this.findViewById(R.id.viewpager);
        this.mToolbarBottom = this.findViewById(R.id.toolbar_bottom);
        this.mUseOrigin = new CheckButton(this.findViewById(R.id.origin_check), R.drawable.rc_origin_check_nor, R.drawable.rc_origin_check_sel);
        this.mSelectBox = new CheckButton(this.findViewById(R.id.select_check), R.drawable.rc_select_check_nor, R.drawable.rc_select_check_sel);
        if(editheaad){
            this.mViewPager.setPagingEnabled(!editheaad);
            this.mBtnSend.setText(getResources().getString(R.string.edu_pic_sel_text_14));
            mIndexTotal.setVisibility(View.GONE);
            this.mToolbarBottom.setVisibility(View.GONE);
        }
    }

    protected void onResume() {
        super.onResume();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4) {
            Intent intent = new Intent();
            intent.putExtra("sendOrigin", this.mUseOrigin.getChecked());
            this.setResult(-1, intent);
        }

        return super.onKeyDown(keyCode, event);
    }

    private int getTotalSelectedNum() {
        int sum = 0;

        for(int i = 0; i < this.mItemList.size(); ++i) {
            if (((EduMyPictureSelectorActivity.PicItem)this.mItemList.get(i)).selected) {
                ++sum;
            }
        }

        if (this.mItemSelectedList != null) {
            sum += this.mItemSelectedList.size();
        }

        return sum;
    }

    private String getTotalSelectedSize() {
        float size = 0.0F;

        int i;
        File file;
        for(i = 0; i < this.mItemList.size(); ++i) {
            if (((EduMyPictureSelectorActivity.PicItem)this.mItemList.get(i)).selected) {
                file = new File(((EduMyPictureSelectorActivity.PicItem)this.mItemList.get(i)).uri);
                size += (float)(file.length() / 1024L);
            }
        }

        if (this.mItemSelectedList != null) {
            for(i = 0; i < this.mItemSelectedList.size(); ++i) {
                if (((EduMyPictureSelectorActivity.PicItem)this.mItemSelectedList.get(i)).selected) {
                    file = new File(((EduMyPictureSelectorActivity.PicItem)this.mItemSelectedList.get(i)).uri);
                    size += (float)(file.length() / 1024L);
                }
            }
        }

        String totalSize;
        if (size < 1024.0F) {
            totalSize = String.format("%.0fK", size);
        } else {
            totalSize = String.format("%.1fM", size / 1024.0F);
        }

        return totalSize;
    }

    private void updateToolbar() {
        if(editheaad){
            this.mBtnSend.setText(getResources().getString(R.string.edu_pic_sel_text_14));
            this.mBtnSend.setEnabled(true);
            this.mBtnSend.setTextColor(this.getResources().getColor(R.color.white));
        }else {
            int selNum = this.getTotalSelectedNum();
            if (this.mItemList.size() == 1 && selNum == 0) {
                if(!TextUtils.isEmpty(sendName)){
                    this.mBtnSend.setText(sendName+"");
                }else {
                    this.mBtnSend.setText(R.string.edu_pic_sel_text_1);
                }
                this.mUseOrigin.setText(R.string.edu_pic_sel_text_12);
                this.mBtnSend.setEnabled(false);
                this.mBtnSend.setTextColor(this.getResources().getColor(R.color.color_18));
            } else {
                if (selNum == 0) {
                    if(!TextUtils.isEmpty(sendName)){
                        this.mBtnSend.setText(sendName+"");
                    }else {
                        this.mBtnSend.setText(R.string.edu_pic_sel_text_1);
                    }
                    this.mUseOrigin.setText(R.string.edu_pic_sel_text_12);
                    this.mUseOrigin.setChecked(false);
                    this.mBtnSend.setEnabled(false);
                    this.mBtnSend.setTextColor(this.getResources().getColor(R.color.color_18));
                } else {
                    if(isSelect){
                        if (selNum <= imgMaxNumber) {
                            this.mBtnSend.setEnabled(true);
                            this.mBtnSend.setTextColor(this.getResources().getColor(R.color.white));
                            if(!TextUtils.isEmpty(sendName)){
                                this.mBtnSend.setText(String.format(sendName+"(%d/"+imgMaxNumber+")", selNum));
                            }else{
                                this.mBtnSend.setText(String.format("发送(%d/"+imgMaxNumber+")", selNum));
                            }
                            this.mUseOrigin.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_15), this.getTotalSelectedSize()));
                        }
                    }else {
                        if (selNum <= 9) {
                            this.mBtnSend.setEnabled(true);
                            this.mBtnSend.setTextColor(this.getResources().getColor(R.color.white));
                            if(!TextUtils.isEmpty(sendName)){
                                this.mBtnSend.setText(String.format(sendName+"(%d/9)", selNum));
                            }else{
                                this.mBtnSend.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_5), selNum));
                            }
                            this.mUseOrigin.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_15), this.getTotalSelectedSize()));
                        }
                    }

                }

            }
        }
    }

    @TargetApi(11)
    public static int getSmartBarHeight(Context context) {
        try {
            Class c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("mz_action_button_min_height");
            int height = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(height);
        } catch (Exception var5) {
            var5.printStackTrace();
            return 0;
        }
    }

    private class CheckButton {
        private View rootView;
        private ImageView image;
        private TextView text;
        private boolean checked = false;
        private int nor_resId;
        private int sel_resId;

        public CheckButton(View root, @DrawableRes int norId, @DrawableRes int selId) {
            this.rootView = root;
            this.image = (ImageView)root.findViewById(R.id.image);
            this.text = (TextView)root.findViewById(R.id.text);
            this.nor_resId = norId;
            this.sel_resId = selId;
            this.image.setImageResource(this.nor_resId);
        }

        public void setChecked(boolean check) {
            this.checked = check;
            this.image.setImageResource(this.checked ? this.sel_resId : this.nor_resId);
        }

        public boolean getChecked() {
            return this.checked;
        }

        public void setText(int resId) {
            this.text.setText(resId);
        }

        public void setText(CharSequence chars) {
            this.text.setText(chars);
        }

        public void setOnClickListener(@Nullable View.OnClickListener l) {
            this.rootView.setOnClickListener(l);
        }
    }

    private class PreviewAdapter extends PagerAdapter {
        private PreviewAdapter() {
        }

        public int getCount() {
            return EduMyPicturePreviewActivity.this.mItemList.size();
        }

        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            final PhotoView photoView = new PhotoView(container.getContext());
            photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                public void onViewTap(View view, float x, float y) {
                    EduMyPicturePreviewActivity.this.mFullScreen = !EduMyPicturePreviewActivity.this.mFullScreen;
                    View decorView;
                    byte uiOptions;
                    if (EduMyPicturePreviewActivity.this.mFullScreen) {
                        if (Build.VERSION.SDK_INT < 16) {
                            EduMyPicturePreviewActivity.this.getWindow().setFlags(1024, 1024);
                        } else {
                            decorView = EduMyPicturePreviewActivity.this.getWindow().getDecorView();
                            uiOptions = 4;
                            decorView.setSystemUiVisibility(uiOptions);
                        }

                        EduMyPicturePreviewActivity.this.mToolbarTop.setVisibility(View.INVISIBLE);
                        EduMyPicturePreviewActivity.this.mToolbarBottom.setVisibility(View.INVISIBLE);
                    } else {
                        if (Build.VERSION.SDK_INT < 16) {
                            EduMyPicturePreviewActivity.this.getWindow().setFlags(1024, 1024);
                        } else {
                            decorView = EduMyPicturePreviewActivity.this.getWindow().getDecorView();
                            uiOptions = 0;
                            decorView.setSystemUiVisibility(uiOptions);
                        }

                        EduMyPicturePreviewActivity.this.mToolbarTop.setVisibility(View.VISIBLE);
                        EduMyPicturePreviewActivity.this.mToolbarBottom.setVisibility(View.VISIBLE);
                    }

                }
            });
            container.addView(photoView, -1, -1);
            String path = ((EduMyPictureSelectorActivity.PicItem)EduMyPicturePreviewActivity.this.mItemList.get(position)).uri;
            AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
            AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
            Bitmap bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, 0, 0, new AlbumBitmapCacheHelper.ILoadImageCallback() {
                public void onLoadImageCallBack(Bitmap bitmap, String p, Object... objects) {
                    if (bitmap != null) {
                        photoView.setImageBitmap(bitmap);
                    }
                }
            }, new Object[]{position});
            if (bitmap != null) {
                photoView.setImageBitmap(bitmap);
            } else {
                photoView.setImageResource(R.drawable.rc_grid_image_default);
            }

            return photoView;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }
    }
}
